package com.tdam2011.grupo05.ui.activities;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.entities.logs.LogImp;
import com.tdam2011.grupo05.services.ServiceHelper;
import com.tdam2011.grupo05.ui.widgets.quickaction.QuickAction;
import com.tdam2011.grupo05.utils.ComparadorContacto;

@SuppressLint("SimpleDateFormat")
public class LogActivity extends ListActivity {

	private final int DIALOG_ORDENAR = 1;

	LogAdapter adapter;
	QuickAction mQuickAction;
	ImageView mMoreIv = null;
	ArrayList<LogImp> acciones = new ArrayList<LogImp>();
	ArrayList<LogImp> filtrados = new ArrayList<LogImp>();
	String idContacto;
	String contactoNom;
	SharedPreferences settingOrden;
	boolean filtroFlag = false;

	public static final String TAG = "LogActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.log_activity);
		Spinner s = (Spinner) findViewById(R.id.spinner);

		ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter
				.createFromResource(this, R.array.filtroAcciones,
						android.R.layout.simple_spinner_item);
		adapterSpinner
				.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		s.setAdapter(adapterSpinner);

		settingOrden = getPreferences(MODE_PRIVATE);
		idContacto = getIntent().getStringExtra("idContacto");
		contactoNom = getIntent().getStringExtra("nombreContacto");

		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/BIMINR__.TTF");
		TextView empty = (TextView) findViewById(android.R.id.empty);
		empty.setTypeface(tf);

		TextView titulo = (TextView) findViewById(R.id.texto_titulo);
		titulo.setTypeface(tf);
		titulo.setTextSize(22);

		getListView().setOnItemLongClickListener(longClicAction);

		ImageView ordenar = (ImageView) findViewById(R.id.ordenar_titulo);
		ordenar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onCreateDialog(DIALOG_ORDENAR);
			}
		});

		Log.v(TAG, "ID:" + idContacto + " Nombre:" + contactoNom);
		String selection = LogImp.COL_CONTACT_NAME + "=?";
		String[] selectionArgs = { contactoNom };

		Cursor actionCursor = ServiceHelper.getIntance(this).getDataManager()
				.getLogCursor(selection, selectionArgs, null);

		startManagingCursor(actionCursor);

		while (actionCursor.moveToNext()) {
			LogImp accion = new LogImp();
			accion.setId(actionCursor.getLong(actionCursor
					.getColumnIndex(LogImp.COL_ID)));
			accion.setNombreContacto(actionCursor.getString(actionCursor
					.getColumnIndex(LogImp.COL_CONTACT_NAME)));
			accion.setFecha(new Date(actionCursor.getLong(actionCursor
					.getColumnIndex(LogImp.COL_DATE))));
			accion.setTipo(actionCursor.getInt(actionCursor
					.getColumnIndex(LogImp.COL_TYPE)));
			accion.setData(actionCursor.getString(actionCursor
					.getColumnIndex(LogImp.COL_DATA)));

			acciones.add(accion);
		}

		adapter = new LogAdapter(acciones);
		setListAdapter(adapter);

		if (settingOrden.getInt("filtroAcciones", 0) != 0) {

			for (LogImp acc : acciones) {

				if (acc.getTipo() == settingOrden.getInt("filtroAcciones", 0)
						|| acc.getTipo() == settingOrden.getInt(
								"filtroAcciones2", 0)) {
					filtrados.add(acc);
				}

			}

			adapter.setAcciones(filtrados);
			setListAdapter(adapter);

		} else {
			setListAdapter(adapter);
		}

		if (settingOrden.getInt("ordenAcciones", 0) != 1) {
			Collections.sort(adapter.getAcciones());
			Collections.reverse(adapter.getAcciones());
		} else {
			Collections.sort(adapter.getAcciones(), new ComparadorContacto());
		}

		adapter.setAcciones(adapter.getAcciones());
		setListAdapter(adapter);

		s.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				SharedPreferences.Editor prefEditor = settingOrden.edit();
				switch (position) {
				case 0:
					if (filtroFlag) {
						prefEditor.putInt("filtroAcciones", 0);
						adapter.setAcciones(acciones);
					}
					filtroFlag = true;
					break;
				case 1:
					filtrados.clear();
					for (LogImp acc : acciones) {
						if (acc.getTipo() == R.drawable.ic_call_log_list_outgoing_call) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_call_log_list_outgoing_call);
					adapter.setAcciones(filtrados);
					break;

				case 2:
					filtrados.clear();
					for (LogImp acc : acciones) {
						if (acc.getTipo() == R.drawable.ic_sms_log_list_outgoing_sms) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_sms_log_list_outgoing_sms);
					adapter.setAcciones(filtrados);
					break;

				case 3:
					filtrados.clear();
					for (LogImp acc : acciones) {
						if (acc.getTipo() == R.drawable.ic_mms_log_list_outgoing_mms) {
							filtrados.add(acc);
						}
					}
					prefEditor.putInt("filtroAcciones",
							R.drawable.ic_mms_log_list_outgoing_mms);
					adapter.setAcciones(filtrados);
					break;

				default:
					break;
				}
				prefEditor.commit();
				setListAdapter(adapter);

			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
			}

		}

		);

		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {

				mMoreIv = (ImageView) view.findViewById(R.id.log_i_more);
				mMoreIv.setImageResource(R.drawable.ic_list_more_selected2);

			}

		});

	}

	private OnItemLongClickListener longClicAction = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			final LogImp acc = (LogImp) adapter.getItem(position);

			AlertDialog.Builder builder = new AlertDialog.Builder(
					LogActivity.this);
			builder.setTitle(getResources().getString(
					R.string.dialog_delete_option));
			builder.setMessage(R.string.dialog_delete_log);
			builder.setNegativeButton("No",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							ServiceHelper.getIntance(LogActivity.this)
									.getDataManager().deleteLog(acc);
							adapter.deleteAcccion(acc);
							setListAdapter(adapter);
							dialog.dismiss();
						}
					});
			builder.setCancelable(true);
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		}
	};

	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_ORDENAR:
			final CharSequence[] items = { "Fecha", "Tipo" };
			return new AlertDialog.Builder(LogActivity.this)
					.setTitle(R.string.text_dialog_ordenar)
					.setSingleChoiceItems(items,
							settingOrden.getInt("ordenAcciones", 0),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									SharedPreferences.Editor prefEditor = settingOrden
											.edit();
									if (whichButton == 0) {
										Collections.sort(adapter.getAcciones());
										Collections.reverse(adapter
												.getAcciones());
										prefEditor.putInt("ordenAcciones", 0);
										prefEditor.commit();
									} else {
										Collections.sort(adapter.getAcciones(),
												new ComparadorContacto());
										prefEditor.putInt("ordenAcciones", 1);
										prefEditor.commit();
									}
									adapter.setAcciones(adapter.getAcciones());
									setListAdapter(adapter);
									dialog.dismiss();
								}
							})

					.show();

		}
		return null;
	}

	class Holder {
		ImageView log_iconContact;
		TextView log_txtContactName;
		TextView log_txtData;
		TextView log_txtfecha;
		ImageView log_tipo;
	}

	class LogAdapter extends BaseAdapter {

		private LayoutInflater _inflater;
		private ArrayList<LogImp> _acciones;

		public LogAdapter(ArrayList<LogImp> _acciones) {
			super();
			this._acciones = _acciones;
			_inflater = LayoutInflater.from(LogActivity.this);
		}

		@Override
		public int getCount() {
			return _acciones.size();
		}

		@Override
		public Object getItem(int position) {
			return _acciones.get(position);
		}

		@Override
		public long getItemId(int position) {
			return _acciones.get(position).getId();

		}

		public void setAcciones(ArrayList<LogImp> acciones) {
			_acciones = acciones;
		}

		public void deleteAcccion(LogImp accion) {
			_acciones.remove(accion);
		}

		public ArrayList<LogImp> getAcciones() {
			return _acciones;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			Holder holder;
			if (convertView == null) {
				convertView = _inflater.inflate(R.layout.log_item, null);
				holder = new Holder();

				holder.log_iconContact = (ImageView) convertView
						.findViewById(R.id.log_Cimage);
				holder.log_txtContactName = (TextView) convertView
						.findViewById(R.id.log_txtContactName);
				holder.log_txtData = (TextView) convertView
						.findViewById(R.id.log_txtContactNumber);
				holder.log_txtfecha = (TextView) convertView
						.findViewById(R.id.log_txtfechaLlamada);
				holder.log_tipo = (ImageView) convertView
						.findViewById(R.id.log_tipoLlamada);

				convertView.setTag(holder);

			} else {
				holder = (Holder) convertView.getTag();
			}
			LogImp log = _acciones.get(position);

			int imagen = log.getTipo();
			holder.log_iconContact
					.setImageResource(R.drawable.ic_contact_item2);
			/*
			 * holder.log_iconContact.setOnClickListener(new OnClickListener() {
			 * 
			 * @Override public void onClick(View v) { mQuickAction.show(v);
			 * 
			 * } });
			 */
			holder.log_txtContactName.setText(contactoNom);
			holder.log_txtData.setText(log.getData());
			holder.log_txtfecha.setText(log.getFecha().toString());
			holder.log_tipo.setImageResource(imagen);
			return convertView;
		}
	}
}
